#include "flag3control.h"
#include <QHBoxLayout>
#include <QIntValidator>
#include <QDoubleValidator>
#include <QDebug>
#include <QMessageBox>


/**********************************************
* @file       flag3control.cpp
* @brief      json格式
*{
  "flag3": {
    "label1": "joint_0",
    "label2": "degrees",
    "lineedit": "joint_0_lineedit",
    "pushbutton1": {
      "Commands": "joint_0_decrease(x=<value>)",
      "name": "joint_0_decrease"
    },
    "pushbutton2": {
      "Commands": "joint_0_increase(x=<value>)",
      "name": "joint_0_increase"
    },
    "slider1": "joint_0_slider"
  }
}

* @author     yfk
* @date       2025-06-03
**********************************************/

Flag3Control::Flag3Control(QWidget *parent)
    : QWidget(parent)
{
    // 默认空控件，不创建布局
}

Flag3Control::Flag3Control(const QJsonObject &flagDetails, const QString deviceID, QWidget *parent)
    : QWidget(parent)
{
    setupControlLayout(flagDetails);
    mDeviceName = deviceID;
    flagReset = false;
}

void Flag3Control::setupControlLayout(const QJsonObject &flagDetails)
{
    // 1) 给整行容器打名，用于 QSS 选择
    this->setObjectName("jointControlRow");

    // 2) 布局
    QHBoxLayout *hLayout = new QHBoxLayout(this);
    hLayout->setContentsMargins(0, 0, 0, 0);
    hLayout->setSpacing(5);

    // 3) 解析 JSON
    QString labelText      = flagDetails.value("label1").toString();
    QString unitText       = flagDetails.value("label2").toString();
    QString lineEditName   = flagDetails.value("lineedit").toString();
    QJsonObject pushBtn1   = flagDetails.value("pushbutton1").toObject();
    QString pushBtn1Name   = pushBtn1.value("name").toString();
    QJsonObject pushBtn2   = flagDetails.value("pushbutton2").toObject();
    QString pushBtn2Name   = pushBtn2.value("name").toString();
    QString pushBtn2Cmd    = pushBtn2.value("Commands").toString();
    commandMap.insert(labelText, pushBtn2Cmd);
    QJsonObject sliderJson = flagDetails.value("slider1").toObject();
    QString sliderName     = sliderJson.value("name").toString();
    minValue = sliderJson.value("min").toDouble();
    maxValue = sliderJson.value("max").toDouble();

    // 4) 创建并添加控件

    // 标签（只要文字，无背景圆角）
    label = new QLabel(labelText + " :", this);
    label->setObjectName("jointLabel");
    label->setFixedWidth(120);                  // 与 QSS 中的 min-width 保持一致
    label->setAlignment(Qt::AlignCenter);       // ← 关键：文字水平垂直居中
    hLayout->addWidget(label);

    // 减号按钮
    btnDecrease = new QPushButton("-", this);
    btnDecrease->setObjectName(pushBtn1Name);
    hLayout->addWidget(btnDecrease);

    // 滑块
    slider = new QSlider(Qt::Horizontal, this);
    slider->setObjectName(sliderName);
    slider->setMinimum(static_cast<int>(minValue * 100));
    slider->setMaximum(static_cast<int>(maxValue * 100));
    slider->setValue(m_default);
    hLayout->addWidget(slider);

    // 加号按钮
    btnIncrease = new QPushButton("+", this);
    btnIncrease->setObjectName(pushBtn2Name);
    hLayout->addWidget(btnIncrease);

    // 数值显示
    lineEdit = new QLineEdit(this);
    lineEdit->setObjectName(lineEditName);
    lineEdit->setAlignment(Qt::AlignCenter);
    hLayout->addWidget(lineEdit);

    // 单位标签
    unitLabel = new QLabel(unitText, this);
    unitLabel->setObjectName("unitLabel");
    hLayout->addWidget(unitLabel);

    // 验证器 & 默认值
    QDoubleValidator *validator = new QDoubleValidator(minValue, maxValue, 2, this);
    validator->setNotation(QDoubleValidator::StandardNotation);
    lineEdit->setValidator(validator);
    slider->setValue(static_cast<int>(minValue * 100));
    lineEdit->setText(QString::number(minValue, 'f', 2));

    // 信号槽
    connect(slider,      &QSlider::valueChanged,     this, &Flag3Control::onSliderValueChanged);
    connect(lineEdit,    &QLineEdit::editingFinished, this, &Flag3Control::onLineEditEditingFinished);
    connect(btnDecrease, &QPushButton::clicked,      this, &Flag3Control::onBtnDecreaseClicked);
    connect(btnIncrease, &QPushButton::clicked,      this, &Flag3Control::onBtnIncreaseClicked);

    // 5) 添加 QSS 样式
    setStyleSheet(R"(
        /* 整行容器，带圆角背景 */
        QWidget#jointControlRow {
            background: rgba(255,255,255,0.05);
            border-radius: 8px;
            padding: 10px;
            margin-bottom: 15px;
        }
        /* 左侧标签：文字风格，无背景 */
        QLabel#jointLabel {
            min-width: 120px;
            font-size: 16px;
            font-weight: 500;
            color: white;
            background: transparent;
        }
        /* 右侧标签：文字风格，无背景 */
        QLabel#unitLabel {
            min-width: 120px;
            font-size: 16px;
            font-weight: 500;
            color: white;
            background: transparent;
        }
        /* 按钮：36×36 圆形主色 */
        QPushButton {
            width: 36px;
            height: 36px;
            border-radius: 18px;
            background: #1E90FF;
            color: white;
            border: none;
            font-size: 18px;
        }
        QPushButton:hover {
            background: #006FCC;
        }
        /* 滑块 */
        QSlider {
            min-width: 260px;
            height: 8px;
        }
        QSlider::groove:horizontal {
            border-radius: 4px;
            background: qlineargradient(x1:0,y1:0,x2:1,y2:0,
                                       stop:0 #1E90FF, stop:1 #334155);
        }
        QSlider::handle:horizontal {
            width: 20px;
            height: 20px;
            margin: -6px 0;
            border-radius: 10px;
            background: #F0F5FF;
            border: 2px solid #1E90FF;
        }
        /* 数值框 */
        QLineEdit {
            min-width: 60px;
            max-width: 80px;
            height: 36px;
            background: rgba(255,255,255,0.08);
            border: 1px solid #334155;
            border-radius: 6px;
            padding: 0 12px;
            color: white;
            font-size: 16px;
            font-weight: 600;
            text-align: center;
        }
    )");
}

void Flag3Control::onSliderValueChanged(int value)
{
    double v = value / 100.0;
    QString text = QString::number(v, 'f', 2);
    if (lineEdit->text() != text) {  // 避免重复设置导致信号循环
        lineEdit->setText(text);
    }
    //这里你可以emit信号通知外部值变化
    if(!flagReset)
    {
        emit angleChanged(getJointName(), v,commandMap[getJointName()]);
        QString command = commandMap.value(getJointName());
        //qDebug()<<"flagControl3 command = "<<command<<Qt::endl;
        command.replace("<value>",QString::number(v));
        //pubMsg(command);
        flagReset = false;
    }

}


void Flag3Control::onLineEditEditingFinished()
{
    QString text = lineEdit->text();
    bool ok = false;
    double val = text.toDouble(&ok);
    if (!ok) {
        QMessageBox::warning(this, "Invalid Input", "Please enter a valid number.");
        lineEdit->setText(QString::number(slider->value() / 100.0, 'f', 2));
        return;
    }
    if (val < minValue) val = minValue;
    if (val > maxValue) val = maxValue;
    int sliderVal = static_cast<int>(val * 100);
    if (slider->value() != sliderVal) {
        slider->setValue(sliderVal);
    }
}

void Flag3Control::onBtnDecreaseClicked()
{
    int val = slider->value();
    if (val - static_cast<int>(step * 100) >= static_cast<int>(minValue * 100))
        slider->setValue(val - static_cast<int>(step * 100));
}

void Flag3Control::onBtnIncreaseClicked()
{
    int val = slider->value();
    if (val + static_cast<int>(step * 100) <= static_cast<int>(maxValue * 100))
        slider->setValue(val + static_cast<int>(step * 100));
}

void Flag3Control::reset()
{
    //qDebug()<<"reset::"<<getJointName()<<Qt::endl;
    slider->setValue(m_default);
    lineEdit->setText(QString::number(m_default / 100.0, 'f', 2));
    flagReset = true;

}

QLineEdit* Flag3Control::getAngleDisplay() const
{
    return lineEdit;
}

QString Flag3Control::getJointName() const
{
    if (label) {
        QString text = label->text();
        return text.endsWith(" :") ? text.left(text.length() - 2) : text;
    }
    return QString();
}

void Flag3Control::setDefaultPosition(int defaultPosition)
{
    m_default = defaultPosition;
    slider->setValue(m_default);
    lineEdit->setText(QString::number(m_default / 100.0, 'f', 2));
}

void Flag3Control::setRange(double min, double max)
{
    minValue = min;
    maxValue = max;

    // 更新 slider 范围
    slider->setMinimum(static_cast<int>(min * 100));
    slider->setMaximum(static_cast<int>(max * 100));

    // 更新验证器范围
    QDoubleValidator *validator = new QDoubleValidator(min, max, 2, this);
    validator->setNotation(QDoubleValidator::StandardNotation);
    lineEdit->setValidator(validator);
}



void Flag3Control::pubMsg(QString content)
{
    if(m_node)
    {
        QString id = mDeviceName;
        //QString id = "ORS_Cask";
        m_node->publishCmd(id,content);
    }
}


void Flag3Control::attachToNode(QSharedPointer<DeviceNode> node)
{
    if (m_node) {
        disconnect(m_node.data(), &DeviceNode::cmdReceived,
                   this, &Flag3Control::onDataReceived);
        // disconnect(m_node.data(), &DeviceNode::eventReceived,
        //            this, &Flag3Control::onEventReceived);
    }
    m_node = node;
    if (m_node) {
        connect(m_node.data(), &DeviceNode::cmdReceived,
                this, &Flag3Control::onDataReceived);
        // connect(m_node.data(), &DeviceNode::eventReceived,
        //         this, &Flag3Control::onEventReceived);
    }
}



void Flag3Control::onDataReceived(const QString& content)
{
    //qDebug() << "Flag3Control Node Received Statu " << content << Qt::endl;

    // 解析JSON字符串
    QJsonDocument doc = QJsonDocument::fromJson(content.toUtf8());

    // 判断是否成功解析
    if (doc.isObject()) {
        QJsonObject obj = doc.object();

        // 遍历JSON对象的所有键值对
        QJsonObject::const_iterator iter = obj.constBegin();
        QString key;
        QJsonValue value;
        QString valueF;
        while (iter != obj.constEnd()) {
            // 打印每个键和值
            key = iter.key();
            value = iter.value();
            valueF = " ";
            // 根据值的类型
            if(value.isArray())
            {
                QJsonArray jsonArray = value.toArray();
                int i=1;
                QString nameX;
                for (const auto &value : jsonArray) {
                    //nameArray.push_back(value.toDouble());
                    valueF = QString::number(value.toDouble());
                    nameX = key+QString::number(i);
                    //initMsg.insert(nameX,valueF);
                    initMsg[nameX] = valueF;
                    // QMetaObject::invokeMethod(this, [this, nameX, valueF]() {
                    //     updateFieldValue(nameX, valueF);
                    // }, Qt::QueuedConnection);
                    i++;
                }
                ++iter;
                continue;
            }

            if (value.isDouble()) {
                //qDebug() << key << ": " << value.toDouble();
                valueF = QString::number(value.toDouble());
            } else if (value.isBool()) {

                valueF = value.toBool() ? "TRUE" : "FALSE";
            } else if (value.isString()) {
                //qDebug() << key << ": " << value.toString();
                valueF = value.toString();
            } else {
                qDebug() << key << ": unknown type";
            }

            // QMetaObject::invokeMethod(this, [this, key, valueF]() {
            //     updateFieldValue(key, valueF);
            // }, Qt::QueuedConnection);
            initMsg[key] = valueF;
            //initMsg.insert(key,valueF);
            // 前进到下一个键值对
            ++iter;
        }
    } else {
        qDebug() << "Failed to parse JSON." << Qt::endl;
    }
}

